package com.changgou.system.filter;

import com.changgou.system.utils.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.CharArrayReader;
import java.util.List;

/** 鉴权过滤器,用于token验证
 * @Description:
 * @Version: V1.0
 */
public class AuthorizeFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //如果是登录请求放行
        if (request.getURI().getPath().contains("/admin/login")){
            return chain.filter(exchange);
        }
        //获取请求头
        HttpHeaders headers = request.getHeaders();
        //请求头中获取令牌
        String token = headers.getFirst("token");
        //判断请求头中是否有令牌
        if (StringUtils.isEmpty(token)){
            //7. 响应中放入返回的状态吗, 没有权限访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
           return   response.setComplete();
        }
        //如果有令牌,解析令牌
        try{
            JwtUtil.parseJWT(token);
        }catch (Exception e){
            e.printStackTrace();
            //解析令牌出错
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return  response.setComplete();

        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
